Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
Underscore "defaults" from scratch

I've been trying to rewrite the _.defaults method from underscore.js and I keep getting this error:

should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' } to deeply equal { a: 'existing', b: 2, c: 3, d: 4 }

Here's the missing conditions:

-should copy source properties to undefined properties in the destination object and should return the destination object

and my code:

_.defaults = function (destination, source) {
  Object.keys(destination).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The idea in _.defaults is that keys from the source object might be missing entirely in the destination object. So you need to iterate the keys of the source object instead of those of the destination object:

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

Side note: you can write x == null instead of x === null || x === undefined. Saves some precious keystrokes.

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] == null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda